var util = require('../../utils/util.js');
var app = getApp()
// 网关服务地址
var gateUrl = util.getGPSDomain() + '/wxweb/weixin'

var groupId = ''
var phone = ''
Page({
  data: {
    nickName: '',
    groupId: groupId,
    phone: phone,
    loginResult: ''
  },
  onGroupInput: function (e) {
    var value = e.detail.value
    groupId = value
  },
  onPhoneInput: function (e) {
    var value = e.detail.value
    phone = value
  },
  onconfirm: function (e) {
    var value = e.detail.value
    loginToGroup(app.nickName, groupId, phone)
  },
  onLoad: function (e) {
    // 读取URL的参数
    //console.log("[map]e.userType:" + e.userType)
    app.configPage = this

    var groutInfo = util.getStorage('groutInfo')
    if (groutInfo != null) {
      groupId = groutInfo.groupId
      phone = groutInfo.phone
    }
    // console.log('(config)groupId=' + groupId)

    this.setData({ nickName: app.nickName, groupId: groupId, phone: phone, })
  }
})

function loginToGroup(nickName, groupId, phone) {
  // 登陆组织
  wx.request({
    url: gateUrl,
    data: {
      a: encodeURI(nickName),
      cmd: 'logingroup',
      groupid: groupId,
      phone: phone
    },
    success: function (res) {
      console.log('loginToGroup success. result=' + res.data)
      var data = res.data
      var loginResult = ''
      if (data.userInfo && data.userInfo.rights){
        app.rights = data.userInfo.rights
      }
      if (data.role) {
        var role = '组织成员'
        if (data.role == 'manager') {
          role = '组织创建人'
        } else if (data.role == 'admin') {
          role = '组织管理员'
        }
        if (data.role == 'manager' || data.role == 'admin') {
          app.userInfos = data.userInfos
        } else {
          app.userInfos = null
        }
        app.role = data.role
        app.groupId = groupId
        app.phone = phone
        loginResult = '登陆成功。' + '\n组织名称：' + data.group.name + '\n我的角色：' + role + '\n进入[查看我的轨迹]页面可以查看其他组员轨迹。'
        // 系统缓存数据
        var groutInfo = new Object()
        groutInfo.groupId = groupId
        groutInfo.phone = phone
        groutInfo.role = role
        groutInfo.userInfos = data.userInfos
        util.setStorage('groutInfo', groutInfo)
      } else {
        loginResult = '登陆失败。（请加入QQ群申请建组）'
        app.userInfos = null
        app.role = null
        // 系统缓存数据
        util.setStorage('groutInfo', null)
      }
      app.configPage.setData({ loginResult: loginResult })
    },
    fail: function (error) {
      console.log('loginToGroup fail')
    }
  })
}